package com.example.androidframework.ui.goods

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.androidframework.R
import com.example.androidframework.databinding.ActivityGoodsDetailBinding
import com.martin.lib_base.base.BaseActivity
import com.martin.lib_base.bean.PreviewBean
import com.martin.lib_base.ktx.loge
import com.martin.lib_base.bean.XBannerDataBean
import com.martin.lib_base.ktx.logi
import com.martin.lib_base.ktx.refresh
import com.martin.lib_base.ktx.setItemCount
import com.martin.lib_base.ui.PreviewActivity
import com.xuexiang.xui.utils.StatusBarUtils
import org.jsoup.Jsoup

class GoodsDetailActivity : BaseActivity<ActivityGoodsDetailBinding, GoodsDetailViewModel>() {

    override fun getViewModelClass(): Class<GoodsDetailViewModel> {
        return GoodsDetailViewModel::class.java
    }

    override fun layoutId(): Int {
        return R.layout.activity_goods_detail
    }

    override fun beforeSetContentView() {
        super.beforeSetContentView()
        // 沉浸式状态栏
        StatusBarUtils.translucent(this)
    }

    override fun initOnCreate(savedInstanceState: Bundle?) {
        binding.viewModel = viewModel

        if (!intent.getStringExtra("gid").isNullOrEmpty()) {
            viewModel.goodsId = intent.getStringExtra("gid").toString()
            loge("viewModel.goodsId --------------------- ${viewModel.goodsId}")
            viewModel.getGoodsDetailData()
        }

        binding.navBack.setOnClickListener {
            viewModel.goBack()
        }

        viewModel.detailBean.observe(this) {
            // 轮播图
            setupBanner(it.goodsInfo.thumbsFormat)

            // 原价删除线
            binding.oldPrice.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG

            // 服务说明
            binding.rvService.setItemCount(it.goodsInfo.serviceList.size)
            binding.rvService.refresh(it.goodsInfo.serviceList)

            // 店铺信息
            val options =
                RequestOptions().placeholder(com.martin.lib_base.R.drawable.common_placeholder_img)   // 加载中的占位图片
            Glide.with(this).load(it.shopInfo.logo).apply(options).into(binding.shopAvatar)
            binding.shopStar.rating = it.shopInfo.compositePoints.toFloat()
            if (it.shopInfo.status == "1") {
                binding.bzbox.visibility = View.VISIBLE
            } else {
                binding.bzbox.visibility = View.GONE
            }

            // 组装商品详情html
            setupWebView(it.goodsInfo.picturesFormat)

        }

    }

    /**
     * 设置轮播图
     */
    private fun setupBanner(list: List<String>) {
        val bannerList: MutableList<XBannerDataBean> = mutableListOf()

        list.forEach { url ->
            val bannerInfo = XBannerDataBean(url, "")
            bannerList.add(bannerInfo)
        }
        loge("bannerList === $bannerList")
        // 刷新数据之后，需要重新设置是否支持自动轮播
        binding.banner.setAutoPlayAble(bannerList.size > 1)
        binding.banner.setBannerData(bannerList)

        // 加载图片
        binding.banner.loadImage { _, model, view, _ ->
            val bean = model as XBannerDataBean
            Glide.with(this).load(bean.xBannerUrl)
                .into(view as ImageView)
        }

        // 图片点击事件
        binding.banner.setOnItemClickListener { banner, model, view, position ->
            val preList = arrayListOf<PreviewBean>()
            list.forEach {
                val bean = PreviewBean(it)
                preList.add(bean)
            }
            PreviewActivity.start(this, preList, position)
        }
    }

    /**
     * 商品详情webView
     */
    private fun setupWebView(list: List<String>) {
        val stringBuilder = StringBuilder()
        if (list.isNotEmpty()) {
            stringBuilder.append("<p>")
            list.forEach { image ->
                stringBuilder.append("<img src='${image}'>")
            }
            stringBuilder.append("</p>")

            val html = stringBuilder.toString()
            logi("html ----------\n $html")

            val settings: WebSettings = binding.web.settings
            settings.apply {
                javaScriptCanOpenWindowsAutomatically = true

                //设置自适应屏幕，两者合用
                useWideViewPort = true  // 将图片调整到适合webView的大小
                loadWithOverviewMode = true //缩放至屏幕大小

                blockNetworkImage = false //解决图片加载不出来的问题
                allowFileAccessFromFileURLs = true //是否允许跨域
                allowUniversalAccessFromFileURLs = true
            }

            try {
                // 图片宽度撑满屏幕
                val doc = Jsoup.parse(html)
                val elements = doc.getElementsByTag("img")
                elements.forEach { element ->
                    element.attr("width", "100%").attr("height", "auto")
                }
                // 加载html
                binding.web.loadDataWithBaseURL(null, doc.toString(), "text/html", "utf-8", null)

            } catch (e: Exception) {
                // 出错
            }

        }
    }

    companion object {
        fun start(context: Context, gid: String = "") {
            val intent = Intent(context, GoodsDetailActivity::class.java)
            intent.putExtra("gid", gid)
            context.startActivity(intent)
        }
    }
}